/**
 *  用户缓存    {@link LocalCache}
 *  {@link LocalCache#getUsers}      获取缓存的用户
 *  {@link LocalCache#putUser}       添加一个用户
 *  {@link LocalCache#delUser}       删除一个用户
 *  {@link LocalCache#clearUsers}    清空用户的信息
 *
 *  {@link LocalCache#putLoginUser}  存储登录用户信息
 *  {@link LocalCache#getLoginUser}  获取登录用户信息
 *
 *  {@link LocalCache#putCommon}     存放其他字段
 *  {@link LocalCache#getCommon}     获取其他字段
 *  {@link LocalCache#clearCommon}   清空字段
 *
 */
class LocalCache{
    constructor(){
        this.local = window.localStorage;

        //  记录本地登录过的信息
        let users = this.local.getItem("user");
        if(users!=null){
            this.users = JSON.parse(users);
        }
        this.users = this.users == null ? [] : this.users;

        //  记录当前登录的用户
        let loginUser = this.local.getItem("login_user");
        this.loginUser = loginUser;
    }

    getUsers(){
        return this.users;
    }

    putUser(user){
        this.delUser(user);
        this.users.unshift(user);
        this.local.setItem("user",JSON.stringify(this.users))
    }

    delUser(user){
        let len = this.users.length;
        for(let i = 0;i < len;i++){
            if(user.username == this.users[i].username){
                this.users.splice(i,1);
                break;
            }
        }
    }

    clearUsers(){
        this.users = [];
        this.local.setItem("user",JSON.stringify(this.users));
    }

    /*
     *  更新登录的用户
     *  <li>    user处于登录中的用户
     *  <li>    null    表示退出登录，清空里面的数据
     */
    putLoginUser(user){
        if(user == null){
            this.local.removeItem("login_user");
            return;
        }
        this.local.setItem("login_user",JSON.stringify(user));
    }

    /*
     *  获取处于登录状态的用户
     *  <li>    如果本地没有数据，那么表示没有处于登录中的用户
     */
    getLoginUser(){
        let login = this.local.getItem("login_user");
        if(login == null||login==""){
            return null;
        }
        return JSON.parse(login);
    }

    putCommon(k,v){
        this.local.setItem(k,v);
    }

    getCommon(k){
        return this.local.getItem(k);
    }

    clearCommon(k){
        this.local.removeItem(k);
    }
}

let cache = new LocalCache();
export default cache;